<?php

namespace app\admin\controller\auth;

use app\common\controller\Backend;
use think\Db;

/**
 * 中间人管理
 *
 * @icon fa fa-users
 */
class Middleman extends Backend
{

    /**
     * @var \app\admin\model\UserGroup
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Middleman');
        $this->db2 = Db::connect(config('database.db2'));
    }
    /**
     * 查看   
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->db2->name('middleman')->alias('middleman')
                ->field('middleman.*,admin.nickname as anickname,user.nickname as unickname,user.avatar')
                ->join('chbc_admin admin','middleman.salesman_admin_id=admin.id','left')
                ->join('chbc_user user','middleman.user_id=user.id','left')
                ->where($where)
                ->where(['middleman.no'=>0])
                ->order($sort, $order)
                ->paginate($limit);
            $list2 = $list->items();
            foreach ($list2 as $k => &$row) {
                $admin = ['nickname' => $row['anickname']];
                $row['admin'] = $admin;
                $user = ['avatar' => $row['avatar'],'nickname' => $row['unickname']];
                $row['user'] = $user;
            }
            $result = array("total" => $list->total(), "rows" => $list2);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $salesmanList = $this->salesmanList();
        $this->view->assign("salesmanList", $salesmanList);
        return $this->view->fetch();    
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $salesmanList = $this->salesmanList();
        $this->view->assign("salesmanList", $salesmanList);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function item()
    {
        $ids = input('ids',0);
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $shop_nos = Db::name('shop')->where(['middleman_id2'=>$ids])->value('group_concat(shop_no)');
            if (!$shop_nos) {
                $result = array("total" => 0, "rows" => []);

                return json($result);
            }
            $model = new \app\common\model\Order();
            $list = $model
                ->where($where)
                ->with(['shop', 'user', 'play'])
                ->where('order.shop_no in ('.$shop_nos.')')
                ->order('id desc')
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v['proof'] = [];
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->view->assign("ids", $ids);
        return $this->view->fetch();
    }

}
